package de.uni.muenster.idw2.threads;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import de.uni.muenster.idw2.data.BBBuilding;
import de.uni.muenster.idw2.data.Building;
import de.uni.muenster.idw2.db.DBHelper;
import de.uni.muenster.idw2.interfaces.BuildingMapInterface;
import de.uni.muenster.idw2.xml.OFMXMLParser;

public class BuildingLoaderThread extends AsyncTask<Void, Integer, Building>{
	
	private final BuildingMapInterface act;
	private ProgressDialog progressDialog;
	private final BBBuilding bbBbuilding;

	public BuildingLoaderThread(BBBuilding building, BuildingMapInterface act){
		this.act = act;
		this.bbBbuilding = building;
		
		progressDialog = new ProgressDialog((Context) act);
		progressDialog.setMessage("Loading...");
		
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressDialog.show();
	}

	@Override
	protected Building doInBackground(Void... params) {
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			Log.e("wichtig", e.toString());
		}
		
		OFMXMLParser parser = new OFMXMLParser();
		Building building = parser.getBuilding(bbBbuilding.getPath());
		
		if(building != null){
			DBHelper dbHelper = new DBHelper((Activity) act);
			dbHelper.addBuilding(bbBbuilding);
			dbHelper.closeDB();
		}
		
		return building;
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
	}
	
	@Override
	protected void onPostExecute(Building result) {
		if(result != null){
		act.loadMap(result); //here the map will be shown
		}
		else{
			Toast.makeText((Context) act, "Bad Connection", 4);
		}
		progressDialog.dismiss();
		
	}
	
	@Override
	protected void onCancelled() {
		super.onCancelled();
	}
	

}
